# -*- encoding:utf-8 -*-

from taobao.ApiConstants import *
from taobao.convert import Converter
from taobao.response import TaobaoListResponse

import simplejson as json


# define dict: <Taobaomodel>  <[JsonAttr, callbackFunc]>
# keys: Taobaomodel
# values: [JsonAttr, callbackFunc]
MAPPING = {'Item': ['items', 'ConvertJsonToItem'], 
                    'ItemSearch': ['itemsearchs', 'ConvertJsonToItemSearch']
                    
                    
                    
                    }

class JsonConverter(Converter):

    def __init__(self):
        pass

    def toResponseList(self, rsp, model):
        rspList = TaobaoListResponse()
        rspList.setBody(rsp)
        
        # convert model to TaobaoResponse
        jsonObj = json.loads(rsp)
        rspObj = jsonObj.get(RSP, None)
        if not rspObj:
            return rspList
        
        totalResults = rspObj.get(TOTALRESULTS, None)
        if totalResults:
            rspList.setTotalResults(int(totalResults))
        
        # convert  each response json array to taobao object 
        classNameStr = MAPPING[model.__class__.__name__][0]
    
        itemList = []
        for item in rspObj.get(classNameStr, []):
            
            modelObj = self.fromJson(item, model)
            if modelObj:
                itemList.append(modelObj)

        rspList.setTaobaoObject(itemList)
        return rspList

    def toResponse(self, rsp, model):
        rspList = self.toResponseList(rsp, model)
        return rspList

    def ConvertJsonToItem(self, jsonStr, item):
    
        nick = jsonStr.get('nick', "")
        item.setNick(nick)
        iid = jsonStr.get('iid', "")
        item.setIid(iid)
        title = jsonStr.get('title', "")
        item.setTitle(title)
        
        return item

    def ConvertJsonToItemSearch(self, jsonStr, search):
    
        categoryList = jsonStr.get('category_list', [])
        for cate in categoryList:
            pass
        search.setcategoryList(categoryList)

        itemList = jsonStr.get('item_list', [])
        search.setItemList(itemList)
        
        return search

    def fromJson(self, jsonStr, model):
        """convert each json string to taobao object"""
        className = model.__class__
        modelObj = className()

        func_name = MAPPING[model.__class__.__name__][1]
        callback = getattr(self, func_name)
        modelObj = callback(jsonStr, modelObj)

        return modelObj
